package Cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/CookieDome")
public class CookieDome extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/hml;charset=UTF-8");
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("count")){
                    String value = cookies[i].getValue();
                    int i1 = Integer.parseInt(value)+1;
                    if (i1==3){
                        return;
                    }
                    cookies[i].setValue(i1+"");
                    resp.addCookie(cookies[i]);
                }else if ((i==cookies.length-1)){
                    Cookie count = new Cookie("count", "1");
                    resp.addCookie(count);
                }
            }
        } else {
            Cookie count = new Cookie("count", "1");
            resp.addCookie(count);
        }
        PrintWriter writer = resp.getWriter();
        writer.write("欢迎访问");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
